package com.yeu;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * Servlet implementation class Regist
 */
@WebServlet("/Regist")
public class Regist extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Regist() {
		super();
		// TODO Auto-generated constructor stub
	}
	
	/** 获取真实用户IP **/
	public String getRemortIP(HttpServletRequest request) {
		if (request.getHeader("x-forwarded-for") == null) {
			return request.getRemoteAddr();
		} else {
			return request.getHeader("x-forwarded-for");
		}
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=UTF-8"); 
		request.setCharacterEncoding("UTF-8");
		//request.setAttribute("info", "欢迎注册仰恩说");
		//request.getRequestDispatcher("regist.jsp").forward(request, response); //此处重定向不行
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=utf-8"); // 设置响应报文的编码格式
		PrintWriter pw = response.getWriter();
		String userNumber = request.getParameter("userNumber");
		String password = request.getParameter("password");
		String againPassword = request.getParameter("againPassword");
		String choice = request.getParameter("choice");
		String safecode = request.getParameter("safecode");
		String ipAddress = getRemortIP(request);
		String userId = "";
		String mLog = "";
		System.out.println("\nuserNumber：" + userNumber + "\npassword：" + password + "\nagainPassword：" + againPassword + "\nchoice：" + choice + "\nsafecode：" + safecode);

		if (userNumber.equals("") || password.equals("") || againPassword.equals("") || safecode.equals("")) {
			pw.println("请填写完整数据");
			pw.flush();
			return;
		}
		if (!password.equals(againPassword)) {
			pw.println("输入的两次密码不同");
			pw.flush();
			return;
		}
		
		/* 注册逻辑 */
		try {
			Connection connect = DBUtil.getConnect();
			Statement statement = (Statement) connect.createStatement(); // Statement可以理解为数据库操作实例，对数据库的所有操作都通过它来实现
			ResultSet result;

			String sqlQuery = "select * from " + DBUtil.TABLE_PASSWORD + " where userNumber='" + userNumber + "'";

			// 查询类操作返回一个ResultSet集合，没有查到结果时ResultSet的长度为0
			result = statement.executeQuery(sqlQuery); // 先查询同样的账号（比如手机号）是否存在
			if (result.next() && !userNumber.equals("")) { // 已存在 result.next()
				pw.println("该账号已注册，请使用此账号直接登录或使用其他账号注册");
				pw.flush();
				
			} else { // 不存在
				String sqlInsertPass = "insert into " + DBUtil.TABLE_PASSWORD + "(userNumber,userPassword,choice,safecode) values('" + userNumber + "','" + password + "','" + choice + "','" + safecode + "')";
				// 更新类操作返回一个int类型的值，代表该操作影响到的行数
				int row1 = statement.executeUpdate(sqlInsertPass); // 插入帐号密码
				if (row1 == 1) {
					String sqlQueryId = "select userId from " + DBUtil.TABLE_PASSWORD + " where userNumber='" + userNumber + "'";
					ResultSet result2 = statement.executeQuery(sqlQueryId); // 查询新增记录的userId
					if (result2.next()) {
						userId = result2.getInt("userId") + "";
					}
					String sqlInsertInfo = "insert into " + DBUtil.TABLE_USER_INFO + "(userId,userName,userNumber,userHead) values('" + userId + "','" + userNumber + "','" + userNumber + "','head')";
					int row2 = statement.executeUpdate(sqlInsertInfo); // 在用户信息表中插入刚注册的Id
					if (row2 == 1) { // 两个表中都插入成功，从业务角度认定为注册成功
						pw.print("0");
						pw.flush();
						//将日志信息插入日志表
						String sqlInsertLog = "insert into " + DBUtil.TABLE_USER_LOG + "(requestAccount,requestPassWord,requestIP,status) values('" + userNumber + "','" + password +"','" + ipAddress + "','" + mLog + "')";
						statement.executeUpdate(sqlInsertLog); // 插入帐号密码
					}
				} else {
					userId = "";
				}
			}
			//断开数据库连接
			statement.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
	}

}
